<template>
  <!-- f分包商退库修改 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="退库明细"
          name="receivingMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                <BillTop title="分包商退库编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form :model="basicFormData" label-width="150px" :rules="rules"
                    ref="basicFormData"
                    class="demo-ruleForm">
                    <el-row>
                      <el-col :span="12">
                       <el-form-item label="业务类型：" prop="businessType">
                            <el-select v-model="basicFormData.businessType" placeholder="请选择">
                              <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.key"
                                :value="item.value"
                              >
                              </el-option>
                            </el-select>
                       </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="退料人员：" prop="materialReturnPersonnelName">
                          <el-input
                            v-model="basicFormData.materialReturnPersonnelName"
                          >
                           <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="SelectMaterialReturnPersonnelName"></i>
                          </el-input>
                            <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="AddPersonnelName">添加乙方人员</el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="分包商：" prop="subcontractorName">
                          <el-input
                            v-model="basicFormData.subcontractorName"
                          >
                            <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="SelectSubcontractorName"></i>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="退库日期：" prop="returnDate">
                          <el-date-picker
                            v-model="basicFormData.returnDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="退料编号：">
                          {{basicFormData.billNo}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="所属机构：">
                          {{basicFormData.orgName}}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="领用数量：">
                          {{basicFormData.collectedQuantity}}
                         <!-- 计算，读取并汇总退库明细领料数量总和 -->
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="截止上期末退货数量：">
                          {{basicFormData.previousTotalReturnQuantity}}
                          <!-- 读取该分包商上一次退库单中截止本期末数据 -->
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="退库数量：">
                          {{basicFormData.stockReturnQuantity}}
                         <!-- 计算，汇总退库明细数量总和 -->
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="截止本期末退货数量：">
                          {{basicFormData.currentTotalReturnQuantity}}
                          <!-- 计算：退库数量+截止上期末退库数量 -->
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="状态：">
                        {{
                          ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                            basicFormData.state
                          ]
                        }}
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>

            <!-- ------------------------------------------------------------------------------------- -->
          </div>

            <!-- 退库明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            退库明细
                        </div>
                       <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                         <el-button
                                        size="small"
                                        style="background: rgb(75, 178, 255); color: #fff"
                                        @click="selectSub"
                                        >选择分包商库存</el-button
                                    >
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}} ..
                                </span>
                            </div>
                            <el-table
                                class="table"
                                :data="planRepairDtlListCopy"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClassName"
                                @cell-mouse-leave="cellMouseLeave"
                                :cell-class-name="cellClsNm"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                  children: 'children',
                                  hasChildren: 'hasChildren',
                                }"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                ref="table"
                v-sortTable="{ 'tableData': planRepairDtlListCopy, '_this': this, 'ref': 'table' }"
                            >
                                <el-table-column type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                          <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row)"
                                                v-if="$index > 0">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column  prop="materialName" label="物资名称"  min-width="200"
                                    show-overflow-tooltip align="center">
                                </el-table-column>

                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >

                                </el-table-column>
                                 <el-table-column
                                    prop="subcontractorWarehouseName"
                                    label="分包商仓库"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="subItemName"
                                    label="分部分项"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="pickingQuantity"
                                    label="领料数量"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="supplierName"
                                    label="供应商"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="projectDepartmentWarehouseName"
                                    label="项目部仓库"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="previousTotalReturnQuantity"
                                    label="截止上期末退库数量"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="stockReturnQuantity"
                                    label="退库数量"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                  <template slot-scope="{ row,$index }">
                                    <el-input
                                    v-enter-float2="{
                                            set: row,
                                            key: 'stockReturnQuantity'
                                        }"
                                        @input="input(row)"
                                        @blur="blur"
                                        v-model="row.stockReturnQuantity"
                                        clearable
                                        v-if="$index>0"
                                    ></el-input>
                                </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="currentTotalReturnQuantity"
                                    label="截止本期末退库数量"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                 <el-table-column
                                    prop="subcontractorInventoryRemainingQuantity"
                                    label="分包商库存剩余"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

          <!-- 附件信息 -->
                <div id="accessoryCon" class="con">
                    <div class="tabs-title" id="accessory">附件信息</div>
                    <attach-comp :relationId="attachId" bucketName="material" v-if="objFlag.flag5"/>
                    <div class="seize-a-seat" v-else>
                        <i class="el-icon-loading"></i>
                    </div>
                </div>
           <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
         <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
      <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
         <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

      <!-- <el-button type="primary" style="background: #2e61d7" @click="save('basicFormData')"
       v-debounce
        >保存</el-button
      >
      <el-button type="primary" style="background: #2e61d7" @click="submit('basicFormData')"
       v-debounce
        >保存并提交</el-button
      >
       <el-button
            type="primary"
            style="background: #2e61d7"
            v-debounce
            v-if="basicFormData.state === '1'"
            @click="undoAudit"
            >撤回</el-button
          >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >
      <el-button type="danger" size="small" @click="ctDelete" v-if="basicFormData.state === '0'">删除</el-button> -->
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import CommonApi from '@/api/materials/common.js'

import Api from '@/api/materials/subcontractorRetreat.js'
import { mapMutations } from 'vuex'
import {  openAppClient, getUuid, selectDataClient } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            currentRow: {},
            auditState: {}, //按钮状态
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            tableData: [],
            auditHistoryTable: [], //审核历史
            planRepairDtlList: [], //计划明细表格传后端
            planRepairDtlListCopy: [], //列表显示
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'billNo': '',
                'businessType': null,
                'collectedQuantity': 0,
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'materialReturnPersonnelId': '',
                'materialReturnPersonnelName': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'returnDate': '',
                'state': '',
                'stockReturnQuantity': null,
                'currentTotalReturnQuantity': 0,
                'previousTotalReturnQuantity': 0,
                'subcontractorId': '',
                'subcontractorName': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            options: [
                {
                    value: 1,
                    key: '分包合同',
                },
                {
                    value: 2,
                    key: '加工合同',
                },
                {
                    value: 3,
                    key: '销售合同',
                },
                {
                    value: 4,
                    key: '事实合同',
                },
            ],
            rules: {
                businessType: [
                    { required: true, message: '请选择业务类型', trigger: 'change' },
                ],
                materialReturnPersonnelName: [
                    { required: true, message: '请选择退料人员', trigger: 'change' },
                ],
                subcontractorName: [
                    { required: true, message: '请选择分包商', trigger: 'change' },
                ],
                returnDate: [
                    { required: true, message: '请选择退库日期', trigger: 'change' },
                ],

            },
            billId: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            warehouseId: '',
            warehouseName: '',
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1012,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
        }
    },
    computed: {
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.founderId = localStorage.getItem('userId')
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.billId = this.$route.query.billId
        this.getBasicData() //进入页面就获取基本信息数据
        this.getBasicDataList()
        this.getAuditHistory()
        this.getAttach()
        this.AllcollectedQuantity()  //汇总基础信息领用数量
        this.AllCurrentTotalReturnQuantity() //汇总本期末数量
        this.getwarehouse()
        this.getCurrentUnitInfo()
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory', 'auditHistory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),

        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1012,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },

        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billId, //单据Id  ***
                billType: '1012', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },

        //获取仓库  warehouseId: '', //仓库id warehouseName: '', //仓库名称
        getwarehouse () {
            this.$Ajax
                .httpGet({
                    url: '/material/warehouseManagement/getProjectDepartmentWarehouse',
                    params: {
                        orgId: this.orgId,
                    },
                })
                .then(res=>{
                    this.warehouseId = res.billId
                    this.warehouseName = res.name
                    console.log(' this.warehouseId', this.warehouseId)
                    console.log(' this.warehouseName', this.warehouseName)
                })
        },
        blur () {
            this.AllstockReturnQuantity()
            this.AllCurrentTotalReturnQuantity()
        },
        //汇总基础信息退库数量
        AllstockReturnQuantity () {
            let num = 0
            this.planRepairDtlListCopy.forEach(item=>{
                item.children.forEach(a=>{
                    num += Number(a.stockReturnQuantity)
                })
            })
            this.basicFormData.stockReturnQuantity = num
        },
        //汇总基础信息领用数量
        AllcollectedQuantity () {
            this.planRepairDtlListCopy.forEach(item=>{
                let num = 0
                item.children.forEach(a=>{
                    num += Number(a.pickingQuantity)
                })
                this.basicFormData.collectedQuantity = num
            })
        },

        //汇总本期末退库数量
        AllCurrentTotalReturnQuantity () {
            //计算：退库数量+截止上期末退库数量
            if(this.planRepairDtlListCopy.length > 0) {
                this.planRepairDtlListCopy.forEach(a=>{
                    a.children.forEach(b=>{
                        b.currentTotalReturnQuantity = Number( b.previousTotalReturnQuantity) + Number(b.stockReturnQuantity)
                        b.subcontractorInventoryRemainingQuantity = Number(b.pickingQuantity) - Number(b.stockReturnQuantity) //库存剩余
                    })
                })
            }
            this.basicFormData.currentTotalReturnQuantity = this.basicFormData.stockReturnQuantity + this.basicFormData.previousTotalReturnQuantity
        },

        //选择退料人员()
        SelectMaterialReturnPersonnelName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/personnelOfPartyB/listPersonnelInformationByFilter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify(this.basicFormData.subcontractorId),
                Title: '选择领料人' // 标题
            })
                .then(val => {
                // 保存用户选择返回数据到store
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        this.basicFormData.materialReturnPersonnelName = item.name
                        this.basicFormData.materialReturnPersonnelId = item.dtlId
                    })
                })
        },

        //添加乙方人员
        AddPersonnelName () {
            openAppClient('/materialPartBPerson', '添加乙方人员', function () {
            })
        },
        //选择分包商
        SelectSubcontractorName () {
            //和明细弹窗一样  选择 收料单位
            this.selectSub()
        },
        //退库明细  选择分包商库存
        selectSub () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/onSiteMaterialIssuance/listOnSiteMaterialIssuanceStockForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({
                    'businessType': this.basicFormData.businessType,
                    'OrgId': this.orgId,
                    'keyWord': '',
                    'parentId': '0'
                }),
                Title: '选择库存' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    if(this.planRepairDtlListCopy.length > 0) {
                        val.forEach(e=>{
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            e.materialClassNameArr.shift()
                            e.materialClassIdArr.shift()
                            const obj = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                'billId': this.billId, //分包商退库id
                                'changeType': 1, //
                                'dtlId': '', //分包商退库明细id
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id(
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'pickingQuantity': e.quantity, //领料数量
                                'projectDepartmentWarehouseId': this.warehouseId, //项目部仓库id
                                'projectDepartmentWarehouseName': this.warehouseName, //项目部仓库名称
                                'spec': e.spec, //规格型号
                                'stockReturnQuantity': 0, //退库数量
                                'currentTotalReturnQuantity': 0, //截止本期末退库数量
                                'previousTotalReturnQuantity': 0, //截至上期末退库数量
                                'subItemId': '', //分部分项id
                                'subItemName': '', //分部分项名称
                                'subcontractorInventoryRemainingQuantity': 0, //分包商库存剩余数量
                                'subcontractorWarehouseId': e.warehouseId, //仓库id
                                'subcontractorWarehouseName': e.warehouseName, //仓库名称
                                'supplierId': e.subcontractorId, //供应商id
                                'supplierName': e.subcontractorName, //	供应商名称
                                'texture': e.texture, //材质
                                'unit': e.unit//	计量单位
                            }
                            this.planRepairDtlListCopy.forEach(item=>{
                                item.children.push(obj)
                            })

                            this.getSubReturnPreviousTotalInfo(e)

                        })
                    }else{
                        const mapObj = {}
                        let arr = []
                        val.forEach(e => {
                            //带入基本信息
                            this.basicFormData.subcontractorId = e.subcontractorId
                            this.basicFormData.subcontractorName = e.subcontractorName
                            // this.basicFormData.materialReturnPersonnelName =
                            // this.basicFormData.materialReturnPersonnelId =
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: 0,
                                    totalQuantity: 0,
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            //  物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                'billId': this.billId, //分包商退库id
                                'changeType': 1, //
                                'dtlId': '', //分包商退库明细id
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id(
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'pickingQuantity': e.quantity, //领料数量
                                'projectDepartmentWarehouseId': this.warehouseId, //项目部仓库id
                                'projectDepartmentWarehouseName': this.warehouseName, //项目部仓库名称
                                'spec': e.spec, //规格型号
                                'stockReturnQuantity': 0, //退库数量
                                'currentTotalReturnQuantity': 0, //截止本期末退库数量
                                'previousTotalReturnQuantity': 0, //截至上期末退库数量
                                'subItemId': '', //分部分项id
                                'subItemName': '', //分部分项名称
                                'subcontractorInventoryRemainingQuantity': 0, //分包商库存剩余数量
                                'subcontractorWarehouseId': e.warehouseId, //仓库id
                                'subcontractorWarehouseName': e.warehouseName, //仓库名称
                                'supplierId': e.subcontractorId, //供应商id
                                'supplierName': e.subcontractorName, //	供应商名称
                                'texture': e.texture, //材质
                                'unit': e.unit//	计量单位
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                                // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.stockReturnQuantity || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                            this.getSubReturnPreviousTotalInfo(e)
                        })
                        this.planRepairDtlListCopy = arr
                        this.planRepairDtlList = arr
                    }
                    this.AllstockReturnQuantity()
                    this.AllcollectedQuantity()  //汇总基础信息领用数量
                    this.AllCurrentTotalReturnQuantity() //汇总本期末数量
                })
        },
        // selectSub () {
        //     let val = [{ 'id': '1536998350016671747', 'isDetailed': 1, 'materialClassId': '1492338036615155713/1492338402287161345/1492339386505760770', 'materialClassName': '主要材料/建筑钢材/一级钢材', 'materialId': '1492034311182880769', 'materialName': '钢材0001', 'parentId': '1522783844445122561', 'quantity': 5, 'spec': '规格1', 'stockId': null, 'stockType': 1, 'subcontractorId': '1522783844445122561', 'subcontractorName': '四川公路桥梁建设集团有限公司江习古高速公路项目经理部TJ4分部', 'texture': 'a', 'unit': 'T', 'warehouseId': '1524666021487243266', 'warehouseName': '分包商111' }]
        //     const mapObj = {}
        //     let arr = []
        //     val.forEach(e => {
        //         //带入基本信息
        //         this.basicFormData.subcontractorId = e.subcontractorId
        //         this.basicFormData.subcontractorName = e.subcontractorName
        //         // this.basicFormData.materialReturnPersonnelName =
        //         // this.basicFormData.materialReturnPersonnelId =
        //         const children = []
        //         e.materialClassNameArr = e.materialClassName.split('/')
        //         e.materialClassIdArr = e.materialClassId.split('/')
        //         // TODO: 统计小计
        //         let obj
        //         const topClassId = e.materialClassIdArr.splice(0, 1).toString()
        //         const topClassName = e.materialClassNameArr.splice(0, 1).toString()
        //         if (!mapObj[topClassId]) {
        //             obj = {
        //                 topClassId,
        //                 topClassName,
        //                 customId: topClassId,
        //                 materialClassId: topClassId,
        //                 materialClassName: topClassName,
        //                 uuid: getUuid(),
        //                 totalAmount: 0,
        //                 totalQuantity: 0,
        //             }
        //             //这里需要改成push多个对象   还没改
        //             arr.push(obj)

        //             mapObj[topClassId] = obj
        //         } else {
        //             obj = mapObj[topClassId]
        //         }

        //         //  物资名称
        //         children.push({
        //             uuid: getUuid(),
        //             customId: getUuid(),
        //             'billId': this.billId, //分包商退库id
        //             'changeType': 1, //
        //             'dtlId': '', //分包商退库明细id
        //             'materialClassId': e.materialClassIdArr.join('/'), //物资类别id(
        //             'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
        //             'materialId': e.materialId, //物资id
        //             'materialName': e.materialName, //物资名称
        //             'pickingQuantity': e.quantity, //领料数量
        //             'projectDepartmentWarehouseId': this.warehouseId, //项目部仓库id
        //             'projectDepartmentWarehouseName': this.warehouseName, //项目部仓库名称
        //             'spec': e.spec, //规格型号
        //             'stockReturnQuantity': 0, //退库数量
        //             'currentTotalReturnQuantity': 0, //截止本期末退库数量
        //             'previousTotalReturnQuantity': 0, //截至上期末退库数量
        //             'subItemId': '', //分部分项id
        //             'subItemName': '', //分部分项名称
        //             'subcontractorInventoryRemainingQuantity': 0, //分包商库存剩余数量
        //             'subcontractorWarehouseId': e.warehouseId, //仓库id
        //             'subcontractorWarehouseName': e.subcontractorWarehouseName, //仓库名称
        //             'supplierId': e.subcontractorId, //供应商id
        //             'supplierName': e.subcontractorName, //	供应商名称
        //             'texture': e.texture, //材质
        //             'unit': e.unit//	计量单位
        //         })
        //         obj.children = !obj.children
        //             ? children
        //             : obj.children.concat(children)
        //         // 统计小计
        //         const count = obj.children.reduce(
        //             (prev, c) => (prev += c.stockReturnQuantity || 0),
        //             0
        //         )
        //         obj.materialName = `小计： ${count}`
        //         obj.children = this.uniqueArray(obj.children, 'customId')
        //         this.getSubReturnPreviousTotalInfo(e)
        //     })
        //     this.planRepairDtlListCopy = arr
        //     this.planRepairDtlList = arr
        // },
        // 获取截止上期末信息
        getSubReturnPreviousTotalInfo (e) {
            const params = {
                dtls: [],
                orgId: this.orgId,
                subcontractorId: this.basicFormData.subcontractorId,
            }
            const obj = {
                'materialClassId': e.materialClassId,
                'materialId': e.materialId,
                'quantity': 0,
                'spec': e.spec,
                'subcontractorWarehouseId': e.warehouseId,
                'texture': e.texture,
                'unit': e.unit
            }
            params.dtls.push(obj)
            Api.getSubReturnPreviousTotalInfo(params).then(res=>{
                console.log('res', res)
                if(res.dtls) {
                    res.dtls.forEach(item=>{
                        item.materialClassIdOne = item.materialClassId.split('/')
                        item.materialClassIdOne = item.materialClassIdOne.splice(0, 1).toString()
                        item.materialClassId = item.materialClassId.split('/')
                        item.materialClassId = item.materialClassId.splice(1, 2)
                        item.materialClassId = item.materialClassId.join('/')
                        this.planRepairDtlListCopy.forEach(a=>{
                            a.children.forEach(b=>{

                                if(item.materialClassIdOne === a.materialClassId && item.materialClassId === b.materialClassId && item.materialId === b.materialId && item.spec === b.spec && item.texture === b.texture && item.unit === b.unit && item.subcontractorWarehouseId === b.subcontractorWarehouseId) {
                                    console.log('11111')
                                    b.previousTotalReturnQuantity = res.quantity
                                    this.basicFormData.previousTotalReturnQuantity = res.quantity
                                    b.currentTotalReturnQuantity =  b.previousTotalReturnQuantity + b.stockReturnQuantity
                                    this.AllCurrentTotalReturnQuantity()
                                    b.subcontractorInventoryRemainingQuantity = Number(b.pickingQuantity) - Number(b.stockReturnQuantity) //库存剩余

                                }

                            })
                        })

                    })
                }
            })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //根据分包商退库id查询查询分包商退库基本信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/subcontractorReturnToWarehouse/findById',
                    params: {
                        id: this.billId,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //根据分包商退库id获取分包商退库明细信息
        getBasicDataList () {
            this.$Ajax
                .httpGet({
                    url: '/material/subcontractorReturnToWarehouse/getListById',
                    params: {
                        id: this.billId,
                    },
                })
                .then(res=>{
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.stockReturnQuantity || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })
                    this.planRepairDtlListCopy = res
                    this.planRepairDtlList = res

                })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //保存
        save (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    //基础信息
                    const p1 =  Api.EditSubcontractorRetreat(this.basicFormData)
                    //明细
                    const p2 = Api.EditSubcontractorRetreatList(this.planRepairDtlList)
                    Promise.all([p1, p2]) .then(() => {
                        this.clientPop('suc', '保存成功！', this.$router.go(0))
                    })
                } else {
                    return false
                }
            })
        },
        //提交
        submit (formName) {

            this.$refs[formName].validate(valid => {
                if (valid) {
                    const params = {
                        billId: this.billId, //单据Id  ***
                        billType: '1012', //单据编码  ***
                        dtls: [], //审核中字段值变更历史
                        freeNextUnitIndex: 0, //下一步审核步骤
                        freeNextUser: '', //下一步审核人ID
                        isPass: true, //审核是否通过
                        isShareInAudit: true, //是否共享审核节点
                        opinion: '', //审核意见   ***
                        orgId: this.orgId, //单据机构Id
                        orgName: this.orgName, //单据机构名称
                        userId: this.userId, //审核人Id    ***
                        workId: '', //流程Id
                    }
                    const p1 =  Api.EditSubcontractorRetreat(this.basicFormData)
                    //明细
                    const p2 = Api.EditSubcontractorRetreatList(this.planRepairDtlList)
                    const p3 = CommonApi.AuditCommit(params)
                    Promise.all([p1, p2, p3]).then(() => {
                        this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                    })
                } else {
                    return false
                }
            })
        },
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除单据
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/subcontractorReturnToWarehouse/delete',
                    params: {
                        id: this.billId,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billId,
                billType: '1012',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./subcontractorRetreat')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //获取明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                row.changeType = 2
            }
            if(row.stockReturnQuantity > row.pickingQuantity) {
                this.clientPop(
                    'err',
                    '退库数量不能超过领料数量!',
                )
                setTimeout(()=>{
                    row.stockReturnQuantity = row.pickingQuantity
                })

            }
        },
        //批量删除
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.delete
                )
            }

        },
        //单个删除计划明细
        handleDelete (row, ) {
            console.log(row)
            row.changeType = -1
            // let length = this.errorMsg.length
            //this.planRepairDtlList.splice($index, 1)
            // this.planRepairDtlListCopy.splice($index, 1)
            // if(row.dtlId) {
            //     this.$set(row, 'changeType', -1)
            //     this.planRepairDtlListCopy.splice($index, 1)

            // }else{
            //     this.planRepairDtlList.splice($index, 1)
            //     this.planRepairDtlListCopy.splice($index, 1)

            // }
        },
        //批量删除计划明细
        delete () {
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.dtlId) {
                        this.$set(item, 'changeType', -1)
                        for(let i = this.planRepairDtlListCopy.length; i > 0; i--) {
                            if(this.planRepairDtlListCopy[i - 1] === item) {
                                this.planRepairDtlListCopy.splice(i - 1, 1)
                            }
                        }
                        //汇总金额
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planRepairDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.planRepairDtlList[i - 1] === localArr[j]) {
                                    this.planRepairDtlList.splice(i - 1, 1)
                                    //汇总金额
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.planRepairDtlListCopy[i - 1] === localArr[j]) {
                                    this.planRepairDtlListCopy.splice(i - 1, 1)
                                    //汇总金额
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        //是否进入批量管理
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'changeHistory':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}

</style>